//
//  messageViewController.m
//  TTAddressBook
//
//  Created by 贾政阳 on 11-12-30.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "messageViewController.h"
#import "composeMessageViewController.h"
#import "UICustomView.h"

#define MENUVIEW_TAG    400

#pragma mark messageViewController implementation
@interface messageViewController()
-(void)hideMessageMenu;
@end

@implementation messageViewController
@synthesize table,messageArray,Readmessage,curMessage;
//@synthesize selectedRowIndex;
//@synthesize lastSelectedRowIndex;
//@synthesize opened;

-(id)init{
    if(self = [super init])
    {
        
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}



#pragma mark alertViewDelegate 警告窗口代理

- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	// use "buttonIndex" to decide your action
	//
}

-(void)composFreeMessage{
    [self hideMessageMenu];
    
    composeMessageViewController* freeMessageController = [[composeMessageViewController alloc] init];
    [self.navigationController pushViewController:freeMessageController animated:YES];
    [freeMessageController release];
}
-(void)transmitMessage{
    [self hideMessageMenu];
    
    composeMessageViewController* freeMessageController = [[composeMessageViewController alloc] init];
    freeMessageController.smsText = curMessage;
    [self.navigationController pushViewController:freeMessageController animated:YES];
    [freeMessageController release];
}
//-(void) ChooseWithFlag:(NSInteger)Flag{
//    [self hideMessageMenu];
//    switch (Flag) {
//        case 1:
//            [self composFreeMessage];
//            break;
//            
//        case 2:
//            [self transmitMessage];
//            break;
//            
//        default:
//            break;
//    }
//}

-(void) newMessageMenu{
    [self composFreeMessage];
//    UIButton* backgroundBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
//    [backgroundBtn addTarget:self action:@selector(hideMessageMenu) forControlEvents:UIControlEventTouchUpInside]; 
//    backgroundBtn.backgroundColor = [UIColor clearColor];
//    backgroundBtn.tag = MENUVIEW_TAG;
//    [self.navigationController.view addSubview:backgroundBtn];
//    [backgroundBtn release];
//    
//    UICustomView* MenuView = [[UICustomView alloc] initWithFrame:CGRectMake(170, 50, 127, 87) :@"sms_icon.png":@"x_messenger_icon.png":@"新建信息":@"转发信息"];
//    [self.navigationController.view addSubview:MenuView];
//    MenuView.tag = MENUVIEW_TAG;
//    [MenuView set_Delegate:self];
//    [MenuView release];
    /*
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:0.5];

    [UIView commitAnimations];
     */
}

-(void) hideMessageMenu{
    for(UIView* u in self.navigationController.view.subviews){
        if (u.tag == MENUVIEW_TAG) {
            [u removeFromSuperview];
        }
    } 
}
#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
	// create a new table using the full application frame
	// we'll ask the datasource which type of table to use (plain or grouped)  
    UIBarButtonItem *newMessage = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemCompose)  target:self action:@selector(newMessageMenu)];;
    self.navigationItem.rightBarButtonItem = newMessage;
    [newMessage release];
    MyClass *gs = [MyClass getInstance];
    NSDictionary * ret = [gs getNewMessages:0 limit:8];
    if ([[ret objectForKey:@"total"] intValue] > 0) {
        self.messageArray = [ret objectForKey:@"list"];
        if (messageArray) {
            atStart = [messageArray count];
        }
    }
    
	UITableView *tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] 
														  style:UITableViewStylePlain];
	
	// set the autoresizing mask so that the table will always fill the view
	tableView.autoresizingMask = (UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
	
	// set the cell separator to a single straight line.
	tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
	
	// set the tableview delegate to this object and the datasource to the datasource which has already been set
	tableView.delegate = self;
	tableView.dataSource = self;
	
	//tableView.sectionIndexMinimumDisplayRowCount=10;
    
	// set the tableview as the controller view
    self.table = tableView;
	self.view = tableView;
	[tableView release];
    curRow=-1;
//    selectedRowIndex = lastSelectedRowIndex = -1;
//    opened= NO;
}

-(void)dealloc{
    self.messageArray = nil;
    self.Readmessage=nil;
    [super dealloc];
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    sumheight=0;
    [super viewDidLoad];
}

- (void) updateTable{
    
    NSArray* updateArray = nil;
    
    if (updateArray!=nil && updateArray.count > 0) {
        //table中添加新的内容，更新array和表
        [self.table beginUpdates];
        [self.messageArray insertObjects:updateArray atIndexes:0];
        NSMutableArray *paths = [NSMutableArray arrayWithCapacity:updateArray.count];
        for (int i = 0; i<updateArray.count; i++) {
            [paths addObject:[NSIndexPath indexPathForRow:i inSection:0]];
        }
        [self.table insertRowsAtIndexPaths:paths withRowAnimation:NO];
        [self.table endUpdates];
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];    
    //[self updateTable];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    MyClass *gs = [MyClass getInstance];
    NSDictionary * ret = [gs getNewMessages:0 limit:8];
    if ([[ret objectForKey:@"total"] intValue] > 0) {
        self.messageArray = [ret objectForKey:@"list"];
        if (messageArray) {
            atStart = [messageArray count];
        }
    }
    else {
        self.messageArray = nil;
    }
    sumheight=0;
    [table reloadData];
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.title = @"消息";
}
- (void)viewWillDisappear:(BOOL)animated{
    [self hideMessageMenu];
    MyClass *gs = [MyClass getInstance];
    NSDictionary * ret = [gs markMessagesRead:Readmessage];
    if ([[ret objectForKey:@"code"] intValue] == 0) {
        NSLog(@"成功！");
        [Readmessage removeAllObjects];
    }
    [super viewWillDisappear:animated];
}
- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark table DataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [messageArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *CellIdentifier = @"Cellid";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
		cell.textLabel.font = [cell.textLabel.font fontWithSize:12];
        cell.detailTextLabel.font = [cell.textLabel.font fontWithSize:10];
    }	
	cell.accessoryType = UITableViewCellAccessoryNone;
    for (UIView *subview in cell.subviews) {
        if (subview.tag == 1001)              
            [subview removeFromSuperview];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleGray; 
    NSDictionary*  obj = [self.messageArray objectAtIndex:indexPath.row];

    UILabel* lab1; 
    lab1 = [[UILabel alloc] init];
    lab1.frame = CGRectMake(30, 3, 100, 14);
    lab1.text = [obj objectForKey:@"personShowName"];
    lab1.font = [UIFont boldSystemFontOfSize:14];
    lab1.backgroundColor = [UIColor clearColor];           
    lab1.tag = 1001;
    [cell addSubview:lab1];
    [lab1 release];
    
    UILabel* lab2; 
    lab2 = [[UILabel alloc] init];
    lab2.frame = CGRectMake(220, 3, 100, 14);
    NSDateFormatter*formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"MM月dd日HH:mm"];
    NSString *locationString=[formatter stringFromDate: [obj objectForKey:@"time"]];
    [formatter release];
    lab2.text = locationString;
    lab2.font = [UIFont systemFontOfSize:14];
    lab2.backgroundColor = [UIColor clearColor];           
    lab2.tag = 1001;
    [cell addSubview:lab2];
    [lab2 release];
    UILabel* lab3; 
    lab3 = [[UILabel alloc] init];
    lab3.frame = CGRectMake(30, 20, 280, 45);
    lab3.text = [obj objectForKey:@"content"];
    lab3.font = [UIFont systemFontOfSize:13];
    lab3.backgroundColor = [UIColor clearColor];           
    lab3.tag = 1001;
    //自动换行
    lab3.numberOfLines = 10;
    CGSize size = CGSizeMake(280, 1000);
    CGSize labelSize = [lab3.text sizeWithFont:lab3.font 
                             constrainedToSize:size
                                 lineBreakMode:UILineBreakModeClip];
    
    lab3.frame = CGRectMake(lab3.frame.origin.x, lab3.frame.origin.y,
                            lab3.frame.size.width, labelSize.height);
    
    [cell addSubview:lab3];
    [lab3 release];  
    cell.imageView.image=[UIImage imageNamed:@"blue.png"];
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    //点击删除按钮响应函数
    if (editingStyle == UITableViewCellEditingStyleDelete){
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } 
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    NSInteger tableSumheight;
    if (sumheight < scrollView.frame.size.height)
        tableSumheight = scrollView.frame.size.height;
    else
       tableSumheight = sumheight; 
    if (scrollView.contentOffset.y+scrollView.frame.size.height-40 > tableSumheight) {
        NSMutableArray * arr=[[NSMutableArray alloc] init];
        NSDictionary * ret = [[MyClass getInstance] getNewMessages:atStart limit:8];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            arr = [ret objectForKey:@"list"];
            
            if (arr) {
                atStart = atStart + [arr count];
                [self.messageArray addObjectsFromArray:arr];
            }
        }
    }
    else if (scrollView.contentOffset.y < -20){
            //NSLog(@"往上啦");
        NSDictionary * ret = [[MyClass getInstance] getNewMessages:0 limit:8];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            self.messageArray = [ret objectForKey:@"list"];
            if (messageArray) {
                atStart = [messageArray count];
            }
        }
    }
    [table reloadData];
}


#pragma mark tabl Delegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    double height;
    height=44;
    NSDictionary * obj = [messageArray objectAtIndex:indexPath.row];
    if (obj)
    {
        NSString *message = [obj objectForKey:@"content"];
        CGSize size = CGSizeMake(280, 1000);
        CGSize labelSize = [message sizeWithFont:[UIFont systemFontOfSize:13] 
                                 constrainedToSize:size
                                     lineBreakMode:UILineBreakModeClip];
        

        
       height = labelSize.height+30;
    }
    sumheight+=height;
    return height;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self hideMessageMenu];
    NSDictionary*  obj = [self.messageArray objectAtIndex:indexPath.row];
    self.curMessage = [obj objectForKey:@"content"];
    UITableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.imageView.image = nil;
    if (!Readmessage) {
        Readmessage = [[NSMutableArray alloc] init];
    }
    [self.Readmessage removeObject:[obj objectForKey:@"id"]];
    [self.Readmessage addObject:[obj objectForKey:@"id"]];
    
    detailMessageViewController* view = [[detailMessageViewController alloc] initWithOneContact:obj];
    [self.navigationController pushViewController:view animated:YES];
    [view release]; 
}
 
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return UITableViewCellEditingStyleDelete;
}

@end
